import 'package:dio/dio.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_disposable.dart';
import 'package:get/get_utils/src/extensions/internacionalization.dart';
import 'package:logger/logger.dart';
import 'package:vischat/core/config/app_config.dart';
import 'package:vischat/data/datasources/local/secure_local.dart';

class ApiService extends GetxService {
  final Logger _logger;
  final SecureLocal _secureLocal;
  late final Dio _dio;

  ApiService(this._logger, this._secureLocal);

  @override
  void onInit() async {
    await _initDio(); // 异步初始化
    super.onInit();
  }

  Future<void> _initDio() async {
    final options = BaseOptions(
      baseUrl: AppConfig.baseUrl,
      connectTimeout: const Duration(seconds: 5),
      headers: {'Content-Type': 'application/json'},
    );

    _dio = Dio(options)
      ..interceptors.add(
        InterceptorsWrapper(
          onRequest: (options, handler) async {
            options.headers['Authorization'] = _secureLocal.getToken();
            _logRequest(options);
            return handler.next(options);
          },
          onResponse: (response, handler) {
            _logger.i('Response: ${response.data}');
            return handler.next(response);
          },
          onError: (e, handler) {
            _logger.e('Error: ${e.message}');
            return handler.next(e);
          },
        ),
      );
  }

  void _logRequest(RequestOptions options) {
    _logger.i('''
      Request URL: ${options.uri}
      Method: ${options.method}
      Headers: ${options.headers}
      Body: ${options.data}
    ''');
  }

  // GET 请求
  Future<Response> get(
    String path, {
    Map<String, dynamic>? queryParameters,
  }) async {
    try {
      Response response = await _dio.get(
        path,
        queryParameters: queryParameters,
      );
      return response;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // POST 请求
  Future<Response> post(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
  }) async {
    try {
      Response response = await _dio.post(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return response;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // PUT 请求
  Future<Response> put(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
  }) async {
    try {
      Response response = await _dio.put(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return response;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // DELETE 请求
  Future<Response> delete(
    String path, {
    Map<String, dynamic>? queryParameters,
  }) async {
    try {
      Response response = await _dio.delete(
        path,
        queryParameters: queryParameters,
      );
      return response;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }

  // 错误处理
  String _handleError(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        return 'http.connectionTimeout'.tr;
      case DioExceptionType.sendTimeout:
        return 'http.sendTimeout'.tr;
      case DioExceptionType.receiveTimeout:
        return 'http.receiveTimeout'.tr;
      case DioExceptionType.badResponse:
        return '${'http.badResponse'.tr}: ${e.response?.statusCode}';
      case DioExceptionType.cancel:
        return 'http.cancel'.tr;
      case DioExceptionType.unknown:
        return '${'http.unknown'.tr}: ${e.message}';
      default:
        return 'http.network'.tr;
    }
  }

  @override
  void onClose() {
    _dio.close();
    super.onClose();
  }
}
